package com.moli.iov.down.command.design.command.reshandler.impl;

import com.moli.iov.down.enums.OperatorResultEnum;
import com.moli.iov.down.enums.command.upgrade.UpgradeStatusEnum;
import com.moli.iov.down.model.po.VehicleCommand;
import com.moli.iov.down.command.codec.decode.bean.UpgradeResBean;
import com.moli.iov.down.command.codec.decode.decoders.UpgradeDecoder;
import com.moli.iov.down.command.codec.utils.Protocol;
import com.moli.iov.down.command.design.command.reshandler.ResponseHandlerCommand;
import com.moli.iov.down.command.mq.SendCache;
import com.moli.iov.down.service.IVehicleCommandService;
import com.moli.iov.util.ByteArrayUtil;
import com.moli.iov.util.SpringContextUtils;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>
 * 恒领远程升级命令应答 业务处理
 * </p>
 *
 * @author: zql
 * @Date: 2018/12/29 17:51
 */
public class UpgradeCommand implements ResponseHandlerCommand {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    private SendCache sendCache = SpringContextUtils.getBean("sendCache");
    private IVehicleCommandService vehicleCommandService =
        SpringContextUtils.getBean("vehicleCommandService");

    @Override
    public void execute(Protocol protocol) {
        String data = ByteArrayUtil.toHexString(protocol.getData());
        logger.info("[上行响应报文] [恒领远程升级命令应答响应] vin:{} 数据：{}", 
                protocol.getVin(), data);

        UpgradeDecoder upgradeDecoder = SpringContextUtils.getBean("upgradeDecoder");
        UpgradeResBean decode = upgradeDecoder.decode(protocol.getData());
        decode.setVin(protocol.getVin());

        String status = ByteArrayUtil.toBinary(decode.getStatus());
        String upgradeStatus = ByteArrayUtil.toBinary(decode.getUpgradeStatus());
        logger.info("[上行响应报文] [恒领远程升级命令应答响应] vin:{}, 状态：{}，升级状态：{}，升级日志：{} ",
                protocol.getVin(), status, upgradeStatus, decode.getUpgradeLog());

        updateCahe(decode);

        if(UpgradeStatusEnum.UPADATE_SUCCESSED.getFlag() != decode.getUpgradeStatus()){
            return;
        }
        udpateResult(decode);
    }

    /**
     * 更新缓存状态
     * @param decode
     */
    public void updateCahe(UpgradeResBean decode){
        try{
            sendCache.updateUpgrdateResResult(decode);
        }catch(Exception e){
            logger.error("[恒领远程升级命令应答] [更新缓存状态] 异常", e);
        }
    }

    /**
     * 更新数据库
     * @param decode
     */
    public void udpateResult(UpgradeResBean decode){
        VehicleCommand vehicleCommand = new VehicleCommand();
        vehicleCommand.setVin(decode.getVin());
        vehicleCommand.setResponseNo(Long.parseLong(sendCache.getUpgradeSerialNumber(decode)));
        vehicleCommand.setResult(OperatorResultEnum.SUCCESS.getFlag());
        vehicleCommand.setResponseTime(new Date());

        vehicleCommandService.updateResult(vehicleCommand);
    }
}
